package cn.tedu._05weibo.conmon.exception;

import cn.tedu._05weibo.conmon.response.JsonResult;
import cn.tedu._05weibo.conmon.response.StatusCode;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult dohandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getMessage();
        log.error("MethodArgumentNotValidException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        //获取异常信息
        String data = ex.getMessage();
        //打印错误日志
        log.error("IllegalArgumentException:"+data);
        //{错误码2002 ，操作失败 ，编号不能小于0}
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult dohandleRuntimeException(RuntimeException ex){
        String data= ex.getMessage();
        log.error(("RuntimeException:"+data));
        return JsonResult.fail(data);
    }

    /*@ExceptionHandler
    public JsonResult doThrowable(Throwable ex){
        String data=ex.getMessage();
        log.error("Throwable:"+data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }*/

}
